<template>
  <div class="p-2 page-flex">
    <!-- 顶部搜索卡片（独立模块，效仿周总结样式） -->
    <el-card class="box-card mb-4" shadow="hover" v-show="showSearch">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" class="search-form">
        <el-form-item label="项目选择" prop="proId">
          <el-select v-model="queryParams.proId" placeholder="请选择项目" clearable filterable remote reserve-keyword
            :remote-method="searchProjects" :loading="projectLoading" style="width: 240px" @change="handleProjectChange"
            @visible-change="handleProjectVisibleChange">
            <el-option v-for="project in projectList" :key="project.id"
              :label="`${project.proName} (${project.proNumber})`" :value="project.id" />
            <template #empty>
              <div class="text-center p-2">
                <span v-if="projectSearchKeyword && projectList.length === 0"> 未找到相关项目 </span>
                <span v-else> 请输入项目名称进行搜索 </span>
              </div>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="回款节点" prop="receiveId">
          <el-select v-model="queryParams.receiveId" placeholder="请选择回款节点" clearable filterable
            :loading="receiveLoading" style="width: 240px" :disabled="!queryParams.proId"
            @visible-change="handleReceiveVisibleChange" @change="handleReceiveChange">
            <el-option v-for="receive in receiveList" :key="receive.id" :label="receive.nodeTitle"
              :value="receive.id" />
            <template #empty>
              <div class="text-center p-2">
                <span v-if="!queryParams.proId"> 请先选择项目 </span>
                <span v-else> 未找到相关回款节点 </span>
              </div>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="技术流程" prop="planId">
          <el-select v-model="queryParams.planId" placeholder="请选择技术流程" clearable filterable :loading="planLoading"
            style="width: 240px" :disabled="!queryParams.proId || !queryParams.receiveId"
            @visible-change="handlePlanVisibleChange" @change="handlePlanChange">
            <el-option v-for="plan in planList" :key="plan.id" :label="plan.techFlow" :value="plan.id" />
            <template #empty>
              <div class="text-center p-2">
                <span v-if="!queryParams.proId"> 请先选择项目 </span>
                <span v-else-if="!queryParams.receiveId"> 请先选择回款节点 </span>
                <span v-else> 未找到相关技术流程 </span>
              </div>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="工作内容" prop="flowId">
          <el-select v-model="queryParams.flowId" placeholder="请选择工作内容" clearable filterable :loading="flowLoading"
            style="width: 240px" :disabled="!queryParams.proId || !queryParams.receiveId || !queryParams.planId"
            @visible-change="handleFlowVisibleChange">
            <el-option v-for="flow in flowList" :key="flow.id" :label="flow.workContent" :value="flow.id" />
            <template #empty>
              <div class="text-center p-2">
                <span v-if="!queryParams.planId"> 请先选择技术流程 </span>
                <span v-else> 未找到相关工作内容 </span>
              </div>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="记录时间" prop="logDate" style="width: 308px">
          <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
            start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 工作日志台账卡片（列表卡片） -->
    <el-card class="box-card table-card" v-loading="loading">
      <template #header>
        <el-row :gutter="10" class="mb8" style="align-items:center;">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['project:worklog:export']">导出</el-button>
          </el-col>
          <el-col :span="10" style="display: flex; align-items: center; gap: 8px">
            <el-select v-model="sortField" placeholder="选择排序字段" clearable style="width: 170px"
              @change="handleSortChange">
              <el-option label="记录人" value="logRecorder" />
              <el-option label="记录时间" value="logDate" />
              <el-option label="项目名称" value="proId" />
              <el-option label="付款节点" value="receiveId" />
              <el-option label="技术流程" value="planId" />
              <el-option label="工作内容" value="flowId" />
              <el-option label="修改时间" value="updateTime" />
            </el-select>
            <el-button v-if="sortField" :icon="sortOrder === 'asc' ? 'ArrowUp' : 'ArrowDown'" @click="toggleSortOrder"
              type="info" plain size="small" :title="sortOrder === 'asc' ? '当前为正序，点击切换为逆序' : '当前为逆序，点击切换为正序'">
              {{ sortOrder === 'asc' ? '正序' : '逆序' }}
            </el-button>
          </el-col>
          <div style="margin-left: auto; display: flex; align-items: center; gap:8px;">
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
          </div>
        </el-row>
      </template>

      <!-- 工作日志表格 -->
      <div class="worklog-container">
        <el-table :data="worklogList" border style="width: 100%" row-key="id" :row-class-name="tableRowClassName"
          class="flex-table" :header-cell-style="{'text-align':'center'}">
          <!-- 序号 -->
          <el-table-column label="序号" align="center" width="60" fixed="left">
            <template #default="scope">
              <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <!-- 创建人 -->
          <el-table-column width="110" label="记录人" align="center" fixed="left" prop="logRecorderName">
            <template #default="scope">
              <span>{{ scope.row.logRecorderName || '-' }}</span>
            </template>
          </el-table-column>
          <!-- 记录时间 -->
          <el-table-column width="110" label="记录时间" align="center" fixed="left" prop="item.workTime">
            <template #default="scope">
              <el-date-picker v-if="scope.row.isEditing" v-model="scope.row.logDate" type="date"
                value-format="YYYY-MM-DD" placeholder="选择日期（必填）" style="width: 100%"
                :class="{ 'is-error': !scope.row.logDate }" />
              <span v-else>{{ scope.row.logDate ? parseTime(scope.row.logDate, '{y}-{m}-{d}') : '-' }}</span>
            </template>
          </el-table-column>
          <!-- 项目名称 -->
          <el-table-column width="200" label="项目名称" align="left" fixed="left" prop="proName" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.proName || '-' }}</span>
            </template>
          </el-table-column>
          <!-- 付款节点 -->
          <el-table-column width="200" label="付款节点" align="left" prop="receiveName" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.receiveName || '-' }}</span>
            </template>
          </el-table-column>
          <!-- 技术流程 -->
          <el-table-column width="200" label="技术流程" align="left" prop="techFlow" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.techFlow || '-' }}</span>
            </template>
          </el-table-column>
          <!-- 工作内容 -->
          <el-table-column width="300" label="工作内容" align="left" prop="workContent" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.workContent || '-' }}</span>
            </template>
          </el-table-column>
          <!-- 工作描述 -->
          <el-table-column width="300" label="工作描述" align="left" prop="workDescription">
            <template #default="scope">
              <el-input v-if="scope.row.isEditing" v-model="scope.row.workDescription" type="textarea"
                placeholder="请输入工作描述（必填）" :rows="3" resize="vertical"
                :class="{ 'is-error': !scope.row.workDescription }" />
              <el-tooltip v-else :content="scope.row.workDescription" placement="top"
                :disabled="!scope.row.workDescription">
                <span class="text-overflow">{{ scope.row.workDescription || '-' }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <!-- 工作时长 -->
          <el-table-column width="90" label="工作时长(h)" align="center" prop="workTime">
            <template #default="scope">
              <NumberInput v-if="scope.row.isEditing" v-model="scope.row.workTime" placeholder="工作时长（必填）" :min="0"
                :precision="2" :required="true" :allow-decimal="true" unit="小时"
                :class="{ 'is-error': !scope.row.workTime || scope.row.workTime <= 0 }"
                @change="calculateValidWorkTime(scope.row)" />
              <span v-else>{{ scope.row.workTime || '-' }}</span>
            </template>
          </el-table-column>
          <!-- 审核评分 -->
          <el-table-column width="90" label="审核评分（5分制）" align="center" prop="auditGrade">
            <template #default="scope">
              <NumberInput v-if="scope.row.isEditing" v-model="scope.row.auditGrade" placeholder="1-5分" :min="1"
                :max="5" :precision="2" :step="0.1" :required="true" :allow-decimal="true" unit="分"
                @change="calculateValidWorkTime(scope.row)" />
              <span v-else>{{ scope.row.auditGrade ?? '-' }}</span>
            </template>
          </el-table-column>
          <!-- 有效工作时长 -->
          <el-table-column width="90" label="有效工时(h)" align="center" prop="validWorkTime">
            <template #default="scope">
              <span class="valid-work-time">{{ scope.row.validWorkTime ?? '-' }}</span>
            </template>
          </el-table-column>
          <!-- 备注 -->
          <el-table-column width="150" label="备注" align="left" prop="remark">
            <template #default="scope">
              <el-input v-if="scope.row.isEditing" v-model="scope.row.remark" type="textarea" placeholder="请输入备注"
                :rows="3" resize="vertical" />
              <el-tooltip v-else :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
                <span class="text-overflow">{{ scope.row.remark || '-' }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <!-- 创建时间 -->
          <el-table-column width="110" label="创建时间" align="center" prop="createTime">
            <template #default="scope">
              <span>{{ scope.row.createTime ? parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}</span>
            </template>
          </el-table-column>
          <!-- 操作 -->
          <el-table-column label="操作" width="150" fixed="right" align="center">
            <template #default="scope">
              <template v-if="scope.row.isEditing">
                <el-button size="small" type="primary" @click="saveWorklog(scope.row)" :loading="scope.row.saving"
                  v-hasPermi="['project:worklog:edit']">保存</el-button>
                <el-button size="small" type="danger" @click="cancelEdit(scope.row)" :disabled="scope.row.saving"> 取消
                </el-button>
              </template>
              <template v-else>
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="editWorklog(scope.row)"
                    v-hasPermi="['project:worklog:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button link type="danger" icon="Delete" @click="deleteWorklog(scope.row)"
                    v-hasPermi="['project:worklog:remove']"></el-button>
                </el-tooltip>
              </template>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无工作日志数据" />
          </template>
        </el-table>
      </div>
      <!-- 固定底部分页 -->
      <div class="pagination-container" v-if="worklogList.length > 0">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]" :total="total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { listProWorklog, updateProWorklog, delProWorklog } from '@/api/project/log/worklog';
import { pageListForQuery } from '@/api/project/init/proInfo';
import { getReceiveMoneyNodesByProId } from '@/api/project/receive';
import { listProFlow } from '@/api/project/plan/flow';
import { listProPlan } from '@/api/project/plan';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';
import type { ProFlowVO } from '@/api/project/plan/flow/types';
import { NumberInput } from '@/components/NumberInput';

// 修改 getCurrentInstance 的类型断言
const { proxy } = getCurrentInstance() as any;

// 工作日志列表
const worklogList = ref<any[]>([]);

// 项目和流程相关
const projectList = ref<ProInfoVO[]>([]);
const flowList = ref<ProFlowVO[]>([]);
const planList = ref<any[]>([]);
const receiveList = ref<any[]>([]);
const projectLoading = ref(false);
const flowLoading = ref(false);
const planLoading = ref(false);
const receiveLoading = ref(false);

// 搜索关键词
const projectSearchKeyword = ref('');
const flowSearchKeyword = ref('');
const planSearchKeyword = ref('');
const receiveSearchKeyword = ref('');

// 防抖计时器
let projectSearchTimer: NodeJS.Timeout | null = null;
let flowSearchTimer: NodeJS.Timeout | null = null;
let planSearchTimer: NodeJS.Timeout | null = null;
let receiveSearchTimer: NodeJS.Timeout | null = null;

// 分页参数
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  proId: undefined,
  flowId: undefined,
  // 新增级联查询参数
  // @ts-ignore
  receiveId: undefined as any,
  // @ts-ignore
  planId: undefined as any,
  params: {}
});

// 排序字段与顺序
const sortField = ref<string | undefined>(undefined);
const sortOrder = ref<string>('asc');

// 总条数
const total = ref(0);

// 加载状态
const loading = ref(false);

// 日期范围
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const showSearch = ref(true);
const getList = () => handleQuery();

/**
 * 远程搜索项目
 */
const searchProjects = (query: string) => {
  projectSearchKeyword.value = query;

  if (projectSearchTimer) {
    clearTimeout(projectSearchTimer);
  }

  projectSearchTimer = setTimeout(() => {
    getProjectList(query);
  }, 300); // 300ms防抖
};

// 已移除 remote 搜索，直接按已选上级条件加载选项

/**
 * 获取项目列表
 */
const getProjectList = async (searchKeyword = '') => {
  try {
    projectLoading.value = true;
    const res = await pageListForQuery({
      pageNum: 1,
      pageSize: 50, // 减少单次加载数量
      auditStatus: '3', // 固定携带auditStatus=3参数
      proName: searchKeyword || undefined // 支持名称搜索
    });
    projectList.value = res.rows || [];
  } catch (error) {
    console.error('获取项目列表失败:', error);
    ElMessage.error('获取项目列表失败');
  } finally {
    projectLoading.value = false;
  }
};

/**
 * 获取流程列表
 */
const getFlowList = async (planId: number | string, searchKeyword = '') => {
  if (!planId) {
    flowList.value = [];
    return;
  }

  try {
    flowLoading.value = true;
    const res = await listProFlow({ planId: planId } as any);
    // 只保留需要的字段：id 和 workContent
    flowList.value = (res.data || []).map((flow: any) => ({
      id: flow.id,
      workContent: flow.workContent
    })) as any;
  } catch (error) {
    console.error('获取工作内容列表失败:', error);
    ElMessage.error('获取工作内容列表失败');
    flowList.value = [];
  } finally {
    flowLoading.value = false;
  }
};

// 获取回款节点
const getReceiveList = async (proId: number | string, searchKeyword = '') => {
  try {
    receiveLoading.value = true;
    const res = await getReceiveMoneyNodesByProId(proId);
    const list = res.data || [];
    receiveList.value = list.filter((x: any) => (searchKeyword ? (x.nodeTitle || '').includes(searchKeyword) : true));
  } catch (e) {
    receiveList.value = [];
  } finally {
    receiveLoading.value = false;
  }
};

// 获取计划列表（基于回款节点）
const getPlanList = async (receiveId: number | string, searchKeyword = '') => {
  try {
    planLoading.value = true;
    const res = await listProPlan({ receiveId: receiveId } as any);
    const rows = (res.data || res.rows || []) as any[];
    planList.value = rows.filter((p: any) => (searchKeyword ? (p.techFlow || '').includes(searchKeyword) : true));
  } catch (e) {
    planList.value = [];
  } finally {
    planLoading.value = false;
  }
};

/**
 * 处理项目下拉框显示状态变化
 */
const handleProjectVisibleChange = (visible: boolean) => {
  if (visible && projectList.value.length === 0) {
    getProjectList();
  }
};

/**
 * 处理流程下拉框显示状态变化
 */
const handleFlowVisibleChange = (visible: boolean) => {
  if (visible && queryParams.value.planId && flowList.value.length === 0) {
    getFlowList(queryParams.value.planId as any);
  }
};

// 选择联动
const handleReceiveVisibleChange = (visible: boolean) => {
  if (visible && queryParams.value.proId && receiveList.value.length === 0) {
    getReceiveList(queryParams.value.proId as any, '');
  }
};

const handlePlanVisibleChange = (visible: boolean) => {
  if (visible && queryParams.value.receiveId && planList.value.length === 0) {
    getPlanList(queryParams.value.receiveId as any, '');
  }
};

const handlePlanChange = (val: any) => {
  // 计划改变时清空已选工作内容
  queryParams.value.flowId = undefined;
  flowList.value = [];
  // 主动拉取该计划下的工作内容
  if (val) {
    getFlowList(val, '');
  }
};

const handleReceiveChange = (val: any) => {
  // 回款改变时清空后续
  queryParams.value.planId = undefined;
  queryParams.value.flowId = undefined;
  planList.value = [];
  flowList.value = [];
  // 主动拉取该回款下的技术流程
  if (val) {
    getPlanList(val, '');
  }
};

/**
 * 处理项目选择变化
 */
const handleProjectChange = (value: number | string | undefined) => {
  // 清空下级级联选项
  queryParams.value.receiveId = undefined as any;
  queryParams.value.planId = undefined as any;
  queryParams.value.flowId = undefined;
  receiveList.value = [];
  planList.value = [];
  flowList.value = [];
  receiveSearchKeyword.value = '';
  planSearchKeyword.value = '';
  flowSearchKeyword.value = '';
  // 主动拉取该项目下的回款节点
  if (value) {
    getReceiveList(value, '');
  }
};

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getWorklogListData();
};

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    proId: undefined,
    receiveId: undefined as any,
    planId: undefined as any,
    flowId: undefined,
    params: { beginLogDate: undefined, endLogDate: undefined }
  };

  // 重置排序
  sortField.value = undefined;
  sortOrder.value = 'asc';

  // 清空项目和流程列表
  projectList.value = [];
  receiveList.value = [];
  planList.value = [];
  flowList.value = [];
  projectSearchKeyword.value = '';
  receiveSearchKeyword.value = '';
  planSearchKeyword.value = '';
  flowSearchKeyword.value = '';

  // 清理计时器
  if (projectSearchTimer) {
    clearTimeout(projectSearchTimer);
    projectSearchTimer = null;
  }
  if (flowSearchTimer) {
    clearTimeout(flowSearchTimer);
    flowSearchTimer = null;
  }
  if (planSearchTimer) {
    clearTimeout(planSearchTimer);
    planSearchTimer = null;
  }
  if (receiveSearchTimer) {
    clearTimeout(receiveSearchTimer);
    receiveSearchTimer = null;
  }

  handleQuery();
};

/**
 * 处理排序变化
 */
const handleSortChange = () => {
  if (sortField.value && !sortOrder.value) {
    sortOrder.value = 'asc';
  }
  handleQuery();
};

/**
 * 切换排序顺序
 */
const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
  handleQuery();
};

/**
 * 获取工作日志列表数据
 */
const getWorklogListData = async () => {
  try {
    loading.value = true;
    const params = { ...queryParams.value } as any;

    // 处理日期范围查询
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginLogDate: dateRange.value[0]?.toString(),
        endLogDate: dateRange.value[1]?.toString()
      };
    }

    // 处理排序参数
    if (sortField.value && sortOrder.value) {
      params.orderByColumn = sortField.value;
      params.isAsc = sortOrder.value;
    }

    // 仅当存在时传递级联参数
    if (!params.proId) delete params.proId;
    if (!params.receiveId) delete params.receiveId;
    if (!params.planId) delete params.planId;
    if (!params.flowId) delete params.flowId;

    const res = await listProWorklog(params);
    // 将获取的数据设置为工作日志列表，添加编辑状态标记
    worklogList.value = res.rows.map((item) => ({
      ...item,
      // 确保工作内容回显优先显示 workContent
      workContent: (item as any).workContent ?? (item as any).flowName ?? '',
      isEditing: false,
      saving: false,
      originalData: null
    }));
    total.value = res.total;
  } catch (error) {
    console.error('获取工作日志列表失败:', error);
    ElMessage.error('获取工作日志列表失败');
  } finally {
    loading.value = false;
  }
};

/**
 * 编辑工作日志
 * @param row 工作日志行数据
 */
const editWorklog = (row: any) => {
  try {
    // 保存原始数据用于取消时恢复
    row.originalData = JSON.parse(JSON.stringify(row));
    row.isEditing = true;
    row.saving = false;
  } catch (error) {
    console.error('编辑工作日志失败:', error);
    ElMessage.error('编辑工作日志失败');
  }
};

/**
 * 校验工作日志数据
 * @param row 工作日志行数据
 * @returns 校验结果
 */
const validateWorklogRow = (row: any): { valid: boolean; errors: string[] } => {
  const errors: string[] = [];

  // 必填字段校验
  if (!row.logDate) {
    errors.push('记录时间不能为空');
  }

  if (!row.workTime || row.workTime <= 0) {
    errors.push('工作时长必须大于0');
  } else if (row.workTime > 24) {
    errors.push('工作时长不能超过24小时');
  }

  if (!row.workDescription || row.workDescription.trim() === '') {
    errors.push('工作描述不能为空');
  } else if (row.workDescription.length > 500) {
    errors.push('工作描述不能超过500个字符');
  }

  // 审核评分校验
  if (row.auditGrade !== undefined && row.auditGrade !== null) {
    if (row.auditGrade < 1 || row.auditGrade > 5) {
      errors.push('审核评分必须在1-5分之间');
    }
  }

  // 备注长度校验
  if (row.remark && row.remark.length > 200) {
    errors.push('备注不能超过200个字符');
  }

  // 日期不能是未来日期
  if (row.logDate) {
    const today = new Date();
    const logDate = new Date(row.logDate);
    today.setHours(23, 59, 59, 999); // 设置为当天结束时间
    if (logDate > today) {
      errors.push('记录时间不能是未来日期');
    }
  }

  return {
    valid: errors.length === 0,
    errors
  };
};

/**
 * 保存工作日志
 * @param row 工作日志行数据
 */
const saveWorklog = async (row: any) => {
  // 先进行数据校验
  const validation = validateWorklogRow(row);
  if (!validation.valid) {
    ElMessage.error(`保存失败：${validation.errors.join('；')}`);
    return;
  }

  // 计算有效工作时长
  calculateValidWorkTime(row);

  row.saving = true;
  try {
    const submitData = { ...row };
    delete submitData.isEditing;
    delete submitData.saving;
    delete submitData.originalData;

    await updateProWorklog(submitData);
    ElMessage.success('保存成功');

    row.isEditing = false;
    row.originalData = null;

    // 重新获取数据
    getWorklogListData();
  } catch (error) {
    console.error('保存工作日志失败:', error);
    ElMessage.error('保存失败');
  } finally {
    row.saving = false;
  }
};

/**
 * 取消编辑
 * @param row 工作日志行数据
 */
const cancelEdit = (row: any) => {
  if (row.originalData) {
    // 恢复原始数据
    Object.assign(row, row.originalData);
    row.isEditing = false;
    row.originalData = null;
  }
};

/**
 * 删除工作日志
 * @param row 工作日志行数据
 */
const deleteWorklog = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该工作日志吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await delProWorklog(row.id);
    ElMessage.success('删除成功');
    getWorklogListData();
  } catch (error) {
    // 用户取消或删除失败，不做处理
  }
};

/**
 * 处理分页变化
 */
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  getWorklogListData();
};

const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getWorklogListData();
};

/**
 * 表格行样式
 */
const tableRowClassName = ({ row }: { row: any }) => (row.isEditing ? 'editing-row' : '');

/**
 * 计算有效工作时长
 */
const calculateValidWorkTime = (row: any) => {
  if (row.workTime && row.auditGrade) {
    row.validWorkTime = Number(((row.workTime * row.auditGrade) / 5).toFixed(2));
  } else {
    row.validWorkTime = undefined;
  }
};

/**
 * 导出按钮操作
 */
const handleExport = () => {
  // 构建导出参数，包含当前查询条件
  const params = { ...queryParams.value };

  // 处理日期范围查询
  if (dateRange.value?.length === 2) {
    params.params = {
      ...params.params,
      beginLogDate: dateRange.value[0]?.toString(),
      endLogDate: dateRange.value[1]?.toString()
    };
  }

  // 移除分页参数，导出全部数据
  delete params.pageNum;
  delete params.pageSize;

  // 调用下载方法
  proxy?.download('pro/worklog/export', params, `project_worklog_${new Date().getTime()}.xlsx`);
};

onMounted(() => {
  getWorklogListData();
});
</script>

<style lang="scss" scoped>
/* 页面弹性布局 */
.page-flex {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 16px);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.mb-0 {
  margin-bottom: 0;
}

// 优化圆形刷新按钮样式
:deep(.el-button.circle) {
  min-width: 36px;
  width: 36px;
  height: 36px;
  padding: 0;
  background: #f5f7fa;
  border: 1px solid #dcdfe6;
  box-shadow: none;
  transition:
    box-shadow 0.2s,
    border-color 0.2s;
}

:deep(.el-button.circle):hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.08);
  background: #ecf5ff;
}

.search-section {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #dee2e6;
}

.search-form {
  margin: 0;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  column-gap: 16px;
  row-gap: 12px;
}

.search-form .el-form-item {
  margin: 0 !important;
}

.worklog-container {
  position: relative;
  margin-top: 20px;
  flex: 1;
  overflow: auto;

  :deep(.el-table) {

    // 设置表格内容垂直居中
    .el-table__cell {
      vertical-align: middle;
    }

    // 设置输入框样式
    .el-input,
    .el-input-number,
    .el-date-editor {
      width: 100%;
    }

    // 设置文本域样式
    .el-textarea__inner {
      min-height: 60px;
      resize: vertical;
    }

    // 设置数字输入框样式
    .el-input-number {
      .el-input__wrapper {
        padding-left: 8px;
        padding-right: 8px;
      }
    }
  }
}

/* 固定底部的分页容器，与回款统计布局一致 */
.pagination-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 16px;
  padding: 16px 0;
  border-top: 1px solid #ebeef5;
  background-color: #fff;
  flex-shrink: 0;
}

.text-overflow {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  vertical-align: top;
}

/* 编辑状态行背景色 */
:deep(.editing-row) {
  background-color: var(--el-color-primary-light-9);
}

:deep(.editing-row td) {
  background-color: var(--el-color-primary-light-9) !important;
}

/* 表格内的小尺寸组件调整 */
.worklog-container :deep(.el-input__wrapper) {
  min-height: 28px;
}

.worklog-container :deep(.el-select .el-input__wrapper) {
  min-height: 28px;
}

.worklog-container :deep(.el-date-editor.el-input) {
  width: 100%;
}

.worklog-container :deep(.el-date-editor .el-input__wrapper) {
  min-height: 28px;
}

.worklog-container :deep(.el-textarea__inner) {
  min-height: 60px;
  resize: vertical;
}

.worklog-container :deep(.el-input-number) {
  width: 100%;
}

.worklog-container :deep(.el-input-number .el-input__wrapper) {
  min-height: 28px;
}

/* 让卡片主体成为弹性布局，表格自适应剩余空间 */
.table-card {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.table-card :deep(.el-card__body) {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.flex-table {
  flex: 1;
}

/* 表单验证错误样式 */
.worklog-container :deep(.is-error .el-input__wrapper) {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 1px #f56c6c inset !important;
}

.worklog-container :deep(.is-error .el-input__inner) {
  border-color: #f56c6c !important;
}

.worklog-container :deep(.is-error .el-date-editor .el-input__wrapper) {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 1px #f56c6c inset !important;
}

.worklog-container :deep(.is-error .el-input-number .el-input__wrapper) {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 1px #f56c6c inset !important;
}

/* 悬停时的错误状态 */
.worklog-container :deep(.is-error .el-input__wrapper:hover) {
  border-color: #f56c6c !important;
}

.worklog-container :deep(.is-error .el-date-editor .el-input__wrapper:hover) {
  border-color: #f56c6c !important;
}

.worklog-container :deep(.is-error .el-input-number .el-input__wrapper:hover) {
  border-color: #f56c6c !important;
}

/* 搜索下拉框样式优化 */
:deep(.el-select-dropdown__empty) {
  padding: 16px 0;
  color: #909399;
  font-size: 14px;
}

/* 搜索框提示样式 */
:deep(.el-select .el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

/* 选项样式优化 */
:deep(.el-select-dropdown__item) {
  padding: 10px 20px;
  min-height: 40px;
  line-height: 1.4;
  white-space: nowrap;
  height: auto;
}

:deep(.el-select-dropdown__item.is-hovering) {
  background-color: var(--el-color-primary-light-9);
}

/* 流程选项样式 */
:deep(.flow-option) {
  display: flex;
  align-items: center;
  gap: 0;
  padding: 4px 0;
  width: 100%;
  line-height: 1.4;
}

:deep(.flow-name) {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
  flex-shrink: 0;
}

:deep(.flow-separator) {
  color: #909399;
  font-weight: normal;
  flex-shrink: 0;
  margin: 0 4px;
}

:deep(.flow-content) {
  font-size: 13px;
  color: #666;
  line-height: 1.4;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 有效工作时长样式 */
.valid-work-time {
  font-weight: 600;
  color: #f56c6c;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 8px;
  }

  .card-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .search-section {
    padding: 12px;
  }

  .search-form {
    column-gap: 8px;
    row-gap: 8px;
  }
}
</style>
